package com.wstuo.itsm.web;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Map;
import java.util.Properties;

import javax.servlet.ServletContext;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;

import com.wstuo.common.config.category.service.IEventCategoryService;
import com.wstuo.common.config.dictionary.service.IDataDictionaryGroupService;
import com.wstuo.common.config.dictionary.service.IDataDictionaryItemsService;
import com.wstuo.common.noticeRule.service.INoticeRuleService;
import com.wstuo.configData.service.IConfigDataLoaderService;
import com.wstuo.common.config.category.service.ICICategoryService;
import com.wstuo.common.file.csv.CSVReader;
import com.wstuo.common.jbpm.IJbpmFacade;
import com.wstuo.common.util.AppliactionBaseListener;
/**
 * 默认模块加载
 * @author QXY
 *
 */
public class DefaultModuleLoader implements IModuleLoader{
	final static Logger LOGGER = Logger.getLogger(DefaultModuleLoader.class);
	@Autowired
	private IDataDictionaryGroupService dataDictionaryGroupService;
	@Autowired
	private IDataDictionaryItemsService dataDictionaryItemsService;
	@Autowired
	private INoticeRuleService noticeService;
	@Autowired
	private IJbpmFacade jbpmFacade;//流程
	@Autowired
	private IConfigDataLoaderService configDataLoaderService;
	@Autowired
	private IEventCategoryService eventCategoryService;//常用分类
	private String module;
	private String language;
	private String processKey;
	private String pid;
	private Boolean isHaveProcess;
	private Boolean isHaveNotice;
	/**
	 * 加载全部
	 */
	public void load(String Language,String module,Map<String,String> components){
		language=Language;
		this.module=module;
		ServletContext sc=ServletActionContext.getServletContext();
		setHasProccessAndNotice(module, sc);
		if(components!=null && components.size()>0){
			if(components.get("dictionaryGroup")!=null){
				loadDataDictGroups(components.get("dictionaryGroup"));
			}
			if(components.get("dictionaryItems")!=null){
				loadDataDicts(components.get("dictionaryItems"));
			}
			if(isHaveProcess){
				loadBpm(components.get("bpm"));
			}
			if(module.equals("cim")){
				loadCiCategories(components.get("category"));
			}else{
				loadCategories(components.get("category"));
			}
			if(isHaveNotice){
				loadRule(components.get("rule"));
			}
		}
	}
	/**
	 * 加载流程
	 */
	public void loadBpm(String fileName) {
		jbpmFacade.deployJpdl(getImportFile(module+"/"+fileName));//流程
		getProcessKeyAndId(module);
		configDataLoaderService.processUserCommon(module, processKey, pid);
	}
	/**
	 * 加载规则
	 */
	public void loadRule(String fileName) {
		noticeService.importNotice(getImportFile(module+"/"+fileName));
	}
	/**
	 * 加载报表
	 */
	public void loadReport(String fileName) {
		
	}
	/**
	 *  加载数据字典
	 */
	public void loadDataDicts(String fileName) {
		dataDictionaryItemsService.importDataDictionaryItems(getImportFile(module+"/"+fileName));//数据字典项
	}
	/**
	 * 加载数据分组
	 * @param fileName
	 */
	public void loadDataDictGroups(String fileName){
		dataDictionaryGroupService.importDataDictionaryGroup(getImportFile(module+"/"+fileName));//数据字典分组
	}

	public void loadCategories(String fileName) {
		eventCategoryService.importEventCategory(getImportFile(module+"/"+fileName));//常用分类
	}
	/**
	 * 加载分类
	 */
	private void loadCiCategories(String fileName){
		ApplicationContext ctx=AppliactionBaseListener.ctx;
		ICICategoryService cicategoryService=(ICICategoryService)ctx.getBean("cicategoryService");
		cicategoryService.importCiCategory(getImportFile(module+"/"+fileName));//配置项分类
	}
	/**
	 * 加载其他
	 */
	public void loadOthers(String fileName) {
		
	}
	/**
	 * 加载基础数据
	 * @param module
	 * @param sc
	 * @param Language
	 */
	private void setHasProccessAndNotice(String module, ServletContext sc) {
		try {
			//读取Har包中的资源文件，用于此模块是否有流程或通知规则需要加载
			InputStream inputStream = new FileInputStream(sc.getRealPath("")
					+ "\\propertiesFile\\" + module + ".properties");
			Properties p = new Properties();
			p.load(inputStream);
			isHaveProcess=Boolean.valueOf(p.getProperty("hasProcessDefinition"));
			isHaveNotice=Boolean.valueOf(p.getProperty("hasNotice"));
		} catch (IOException e1) {
			LOGGER.error(e1);
		}

	}
	/**
	 * 获取加载模块的PrcessKey和Id
	 * @param module
	 */
	private void getProcessKeyAndId(String module){
		try{
			Reader rd = new InputStreamReader(new FileInputStream(getImportFile(module+"/processSetting.csv")),"UTF-8");//以字节流方式读取数据
			CSVReader reader=new CSVReader(rd);
			String[] line=reader.readNext();
			processKey=line[0].toString();
			pid=line[1].toString();
		}catch (Exception e) {
			LOGGER.error(e);
		}
	}
	  /**
	   * 公共方法，取得CSV文件路径.
	   * @param fileName 
	   * @return String
	   */
	private String getFilePath(String fileName){
		  return ServletActionContext.getServletContext().getRealPath("")+"/configData/"+language+"/"+fileName;
	  } 
	  
	  /**
	   * 公共方法，取得CSV文件.
	   * @param fileName
	   * @return File
	   */
	private File getImportFile(String fileName){
		  return new File(getFilePath(fileName));
	  }
}
